from django.urls import reverse
import time
import qrcode
import io

def make_survey_url(base_url, pk, expire_time=None, **kwargs):
    target = base_url[:-1] + reverse('survey_detail', args=(pk,)) + "/page"

    if expire_time:
        timestamp = int(time.mktime(expire_time.timetuple()))
        target = target + "?expired=" + str(timestamp)
    
    if kwargs:
        params = []
        for k, v in kwargs.items():
            params.append(f'{k}={v}')
        if "?" in target:
            target = target + '&' + '&'.join(params)
        else:
            target = target + '?' + '&'.join(params)

    return target
    
# 问卷id, 问卷截止时间
def generate_qrcode(url, **kwargs):
    qr_img = qrcode.make(url)
    buffer = io.BytesIO()
    qr_img.save(buffer)
    
    return buffer.getvalue()
